//
//  DatePickerView.m
//  DatePickerView
//
//  Created by 刘琛 on 2017/12/11.
//  Copyright © 2017年 刘琛 All rights reserved.
//

#import "DatePickerView.h"
@interface DatePickerView ()
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *baseViewButtom;
@property (copy, nonatomic) DatePickerViewFailureBlock fail;
@property (copy, nonatomic) DatePickerViewSuccessBlock success;

@property (nonatomic, strong) NSString *miniDate;
@property (nonatomic, strong) NSString *maxDate;

@end
@implementation DatePickerView

+ (void)showDatePickerInView:(UIView *)view
                     success:(DatePickerViewSuccessBlock)success
                     failure:(DatePickerViewFailureBlock)fail {
    
    DatePickerView *dateView = [[[NSBundle mainBundle] loadNibNamed:@"DatePickerView" owner:nil options:nil] firstObject];
    dateView.frame = view.bounds;
    dateView.success = success;
    dateView.fail = fail;
    
    [view addSubview:dateView];
    
    [dateView show];
}

+ (void)showDatePickerInView:(UIView *)view
                    miniDate:(NSString *) miniDate
                     maxDate:(NSString *) maxDate
                     success:(DatePickerViewSuccessBlock) success
                     failure:(DatePickerViewFailureBlock) fail {
    DatePickerView *dateView = [[[NSBundle mainBundle] loadNibNamed:@"DatePickerView" owner:nil options:nil] firstObject];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-mm-dd"];
    
    dateView.datePicker.maximumDate = [formatter dateFromString:maxDate];
    dateView.datePicker.minimumDate = [formatter dateFromString:miniDate];
    dateView.frame = view.bounds;
    dateView.success = success;
    dateView.fail = fail;
    
    [view addSubview:dateView];
    
    [dateView show];
    
}

- (void)show {
    
    [self layoutIfNeeded];
    
    self.baseViewButtom.constant = 0;
    
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
}

- (void)dismiss {
    self.baseViewButtom.constant = -235;
    
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
       [self removeFromSuperview];
    }];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    

}

- (IBAction)cancelButtonAction:(id)sender {
    if (self.fail) {
        self.fail();
    }
    [self dismiss];
}
- (IBAction)okButtonAction:(id)sender {
    if (self.success) {
        self.success(self.datePicker.date);
    }
    [self dismiss];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //    [self clearAll];
    [self dismiss];
}



@end
